package arrray;

/**
 * @author huangxianjin
 * @date 2025/8/17 22:42
 * @description "除自身以外数组的乘积-O(n)时间复杂度"
 */
public class LC_238 {
    //官方做法1-左右乘积列表
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        //当前元素左右元素乘积数组
        int[] L = new int[n];
        int[] R = new int[n];
        //初始化
        L[0] = 1;
        R[n - 1] = 1;

        for (int i = 1; i < n; i++) {
            L[i] = nums[i - 1] * L[i - 1];
        }

        for (int i = n - 2; i >= 0; i--) {
            R[i] = nums[i + 1] * R[i + 1];
        }

        //返回的数组
        int[] answer = new int[n];
        for (int i = 0; i < n; i++) {
            answer[i] = L[i] * R[i];
        }

        return answer;
    }

    //官方做法2-方法1的优化（降低空间复杂度）
    public int[] productExceptSelf2(int[] nums) {
        int n = nums.length;
        int[] answer = new int[n];

        //把answer当做左侧数组
        answer[0] = 1;
        for (int i = 1; i < n; i++) {
            answer[i] = nums[i - 1] * answer[i - 1];
        }

        //右侧乘积用变量R计算，初始化=1
        int R = 1;
        for (int i = n - 1; i >= 0; i--) {
            answer[i] = answer[i] * R;

            R *= nums[i];
        }
        return answer;
    }
}
